﻿var zombies = zombies || {};

zombies.ListMediaType = function () {
    var self = this;
    self.MediaTypes = ko.observableArray();
    self.SearchString = ko.observable("");
    self.CurrentPage = ko.observable(1);
    self.IsPrevious = ko.observable(false);
    self.IsNext = ko.observable(false);
    self.Loaded = ko.observable(false);

    self.SendMsg = function () {
                self.CurrentPage(1);
                load(self.CurrentPage(), self.SearchString());
                $.replaceUrl(self.CurrentPage(), self.SearchString());
    };

    self.EnterSendMsg = function (data, event) {
        try {
            if (event.which === 13) {
                self.CurrentPage(1);
                load(self.CurrentPage(), self.SearchString());
                $.replaceUrl(self.CurrentPage(), self.SearchString());
                return false;
            }
            return true;
        }
        catch (e)
        { }
    }

    self.MediaTypeId = ko.observable();
    self.Name = ko.observable();
    self.Description = ko.observable();
    self.IconPath = ko.observable();
    self.Mime = ko.observable();

    self.MediaTypeData = ko.observable({
        MediaTypeId: self.MediaTypeId,
        Name: self.Name,
        Description: self.Description,
        IconPath: self.IconPath,
        Mime: self.Mime
    });

    self.getEditItem = function (item) {
        self.MediaTypeId(item.MediaTypeId);
        self.Name(item.Name);
        self.Description(item.Description);
        self.IconPath(item.IconPath);
        self.Mime(item.Mime);
    }

    self.doEdit = function (formElement) {
        var mediatype = ko.utils.arrayFirst(self.MediaTypes(), function (item) {
            return item.MediaTypeId === self.MediaTypeId();
        });
        if ($(formElement).valid()) {
            $.ajax({
                type: "PUT",
                url: "/api/AdminMediaType/PutMediaType",
                data: ko.toJSON(self.MediaTypeData), //Convert the Observable Data into JSON
                contentType: "application/json",
                dataType: 'json'
            }).done(function () {
                toastr.success('Sửa Định Dạng QC Thành Công');
                self.MediaTypes.replace(mediatype, { MediaTypeId: self.MediaTypeId(), Name: self.Name(), Description: self.Description(), IconPath: self.IconPath() });
                $('#editmedia-div').removeClass('active in');
                $('#listmedia-div').addClass('active in');
            }).fail(function () {
                toastr.error('Sửa Thất Bại.');
            });
        }
    }

    self.doNext = function () {
        if (self.IsNext()) {
            var page = self.CurrentPage();
            page++;
            self.CurrentPage(page);
            load(page, self.SearchString);
            if (page == 1) {
                self.IsPrevious(false)
            } else {
                self.IsPrevious(true);
            }
            $.replaceUrl(page, self.SearchString());
        }
    }

    self.doPrevious = function () {
        if (self.IsPrevious()) {
            var page = self.CurrentPage() - 1;
            self.CurrentPage(page);
            load(page, self.SearchString);
            if (page == 1) {
                self.IsPrevious(false)
            } else {
                self.IsPrevious(true);
            }
            $.replaceUrl(page, self.SearchString());
        }
    }

    self.mimeList = ko.observableArray(
        [
            { name: "Video embed", value: "embed" },
            { name: "Flash(swf)", value: "application/x-shockwave-flash" },
            { name: "Images(*)", value: "image/*" },
            { name: "Video(*)", value: "video/*" }
        ]
    );
}

var load = function (id, searchString) {
    viewModel.MediaTypes.removeAll();
    $.ajax({
        url: '/api/AdminMediaType/GetMediaTypes/' + id,
        type: 'GET',
        data: { value: searchString },
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (items) {
        if (items.length === 11) {
            items.pop();
            viewModel.IsNext(true);
        } else {
            viewModel.IsNext(false);
        }
        $.each(items, function (idx, item) {
            viewModel.MediaTypes.push(new zombies.MediaType(item));
        });
        viewModel.Loaded(true);
    }).error(function () {
        toastr.error('error');
    })
};

ko.bindingHandlers.fileUpload = {
    init: function (element, valueAccessor) {
        $(element).after('<div class="progress" style="display: none; width: 50%"><div class="bar"></div><div class="percent">0%</div></div><div class="progressError"></div>');
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var options = ko.utils.unwrapObservable(valueAccessor()),
            property = ko.utils.unwrapObservable(options.property),
            url = ko.utils.unwrapObservable(options.url);

        if (property && url) {
            $(element.form).change(function () {
                if (element.files.length)
                    viewModel.IconPath("../Images/MediaType/" + $('#upload').prop("files")[0].name);
            });
            $(element.form).submit(function () {
                if ($(element.form).valid() && element.files.length) {
                    var $this = $(element),
                        filename = $this.val();
                    // this uses jquery.form.js plugin
                    $(element.form).ajaxSubmit({
                        url: url,
                        type: "POST",
                        dataType: "json",
                        headers: { "Content-Disposition": "attachment; filename=" + filename },
                        beforeSubmit: function () {
                            $(".progress").show();
                            $(".progressError").hide();
                            $(".bar").width("0%")
                            $(".percent").html("0%");
                        },
                        uploadProgress: function (event, position, total, percentComplete) {
                            var percentVal = percentComplete + "%";
                            $(".bar").width(percentVal)
                            $(".percent").html(percentVal);
                        },
                        success: function (data) {
                            $(".progress").hide();
                            $(".progressError").hide();
                            // set viewModel property to IconPath
                            bindingContext.$data[property](data);
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            $(".progress").hide();
                            $("div.progressError").html(jqXHR.responseText);
                        }
                    });
                }
            });
        }
    }
}


var viewModel;
$(document).ready(function () {

    viewModel = new zombies.ListMediaType();

    ko.applyBindings(viewModel, document.getElementById("admin_content"));

    var pageUrl = $.getUrlVars("page");
    var searchStringUrl = $.getUrlVars("searchString");
    if (typeof pageUrl === 'undefined' || !isFinite(String(pageUrl))) {
        viewModel.CurrentPage(1);
    } else {
        viewModel.CurrentPage(pageUrl);
    }
    if (typeof searchStringUrl === 'undefined') {
        viewModel.SearchString("");
    } else {
        viewModel.SearchString(searchStringUrl);
    }
    if (pageUrl > 1) viewModel.IsPrevious(true);
    load(viewModel.CurrentPage(), viewModel.SearchString());
});